package com.example.myandroiduseflutter

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.example.myandroiduseflutter.databinding.FragmentAndroidMainBinding
import io.flutter.embedding.android.FlutterFragment
import androidx.fragment.app.FragmentTransaction
import com.example.myandroiduseflutter.databinding.FragmentFlutterMainBinding

import android.widget.FrameLayout
import io.flutter.embedding.android.FlutterView
import io.flutter.embedding.engine.dart.DartExecutor

import io.flutter.embedding.engine.FlutterEngine


/**
 * @author tgw
 * @date 2021/10/8
 * @describe
 */
class CustomFlutterFragment : FlutterFragment() {


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view: FragmentFlutterMainBinding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_flutter_main, container, false)

        val flutterEngine1 = FlutterEngine(context)
        flutterEngine1.dartExecutor.executeDartEntrypoint(
            DartExecutor.DartEntrypoint.createDefault()
        )
        flutterEngine1.navigationChannel.setInitialRoute("homePage")


        // 通过FlutterView引入Flutter编写的页面
        val flutterView = FlutterView(context)
        // 关键代码，将Flutter页面显示到FlutterView中
        flutterView.attachToFlutterEngine(flutterEngine1)

        val lp = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        val flContainer: FrameLayout = view.root.findViewById(R.id.fl_container1)
        flContainer.addView(flutterView, lp)


        return view.root
    }


}